import React, { useCallback, useState, useEffect } from "react";
import { NextPage } from "next";
import cls from "classnames";
import InfinityScroll from "react-infinite-scroller";

import style from "./index.module.scss";
import { Recommend } from "@/components/Recommend";
import { Categories } from "@/components/Categories";
import { Tags } from "@/components/Tags";
import { Footer } from "@/components/Footer";
import { useAffix } from "@/components/Header/useAffix";
import { ArticleApi } from "@/api/article";
import { ArticleList } from "@/components/ArticleList";
import { Icon } from "antd";

const pageSize = 8;

const Category: NextPage = porps => {
  const {
    categorys,
    tags,
    category: categoryValue,
    setting,
    articles: defaultArticles = [],
    total
  } = porps as any;
  const [articles, setArticles] = useState(defaultArticles);
  // const [affix, affixVisible] = useAffix(64, true);
  const [page, setPage] = useState(1);
  const current = categorys.find(c => c.value === categoryValue);

  useEffect(() => {
    setArticles(defaultArticles);
  }, [categoryValue]);
  const getArticles = useCallback(page => {
    ArticleApi.getArticlesByTag(current, {
      page,
      pageSize,
      status: "publish"
    }).then(res => {
      setArticles(articles => [...articles, ...res[0]]);
      setPage(page);
    });
  }, []);
  return (
    <div className={style.wrapper}>
      <div className="container">
        <div className={style.content}>
          <div className={style.head}>
            <Icon className={style.icon} type="appstore" />
            <p>
              <span className={style.primary}>{current?.label}</span>
              分类下的文章
            </p>
          </div>
          <div className={style.list}>
            <InfinityScroll
              pageStart={1}
              loadMore={getArticles}
              hasMore={page * pageSize < total}
              loader={
                <div className={style.loading} key={0}>
                  正在获取文章...
                </div>
              }
            >
              <ArticleList articles={articles} />
            </InfinityScroll>
          </div>
          <aside className={cls(style.aside)}>
            <div /** className={cls(affix ? style.affix : null)} */>
              <Recommend />
              <Categories categorys={categorys} />
              <Tags tags={tags} />
              <Footer setting={setting} />
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
};

Category.getInitialProps = async ctx => {
  const { category } = ctx.query;
  const res = await ArticleApi.getArticlesByCategory(category, {
    page: 1,
    pageSize,
    status: "publish"
  });
  // 服务端返回数据，不需要footer
  return { category, articles: res[0], total: res[1], needLayoutFooter: false };
};

export default Category;
